struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    int countNodes(TreeNode* root) {
        return root == nullptr ? 0 : op(root, 1);
    }

    static int op(TreeNode* node, int cur) {
        int left = cur;
        int right = cur;
        if (node->right != nullptr) {
            right = op(node->right, (cur << 1) + 1);
        }
        if (node->left != nullptr) {
            left = op(node->left, cur << 1);
        }
        return left >= right ? left : right;
    }
};